<template>
	<div ref="chartDom" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import { ref, defineProps, watch, nextTick, onMounted, onUnmounted } from 'vue';
import * as Echarts from 'echarts';

const chartDom = ref(null);
const myChart = ref(null);

const props = defineProps({
	data: {
		type: Object,
		default: ()=> {
			return {}
		}
	},
	title: {
		type: String,
	}
});


const options = ref({
	grid: {
		top: 40,       // 增加顶部空间
		left: 40,      // 增加左侧空间
		right: 20,
		bottom: 10,    // 增加底部空间
		containLabel: true
	},
	title: {
		text: '',
		left: 'left',
		textStyle: {
			fontSize: 14,
			color: '#fff'
		},
		top: 0 // 标题紧贴顶部
	},
	xAxis: {
		type: 'category',
		boundaryGap: true,  // 改为true保留边距
		data: [],
		axisLabel: {
			verticalAlign: 'top',
			color: '#fff',
			margin: 8  // 增加标签外边距
		},
		axisTick: {
			alignWithLabel: true,
			interval: 0  // 强制显示所有刻度
		},
		offset: 0  // 移除偏移量
	},
	yAxis: {
		type: 'value',
		axisLabel: {
			color: '#fff',
			margin: 10,
			verticalAlign: 'bottom' // Y轴标签向下对齐
		},
		axisTick: {
			alignWithLabel: true
		},
		nameTextStyle: {
			color: '#ccc'
		},
		splitLine: {
			show: false
		},
		lineStyle: {
			color: '#ccc'
		},
	},
	tooltip: {
		show: true,
	},
	series: [
		{
			data: [],
			barWidth: '60%',  // 调宽柱子
			type: 'bar',
			// 新增barGap配置
			barGap: '30%',   // 柱子间距控制
			itemStyle: {
				borderRadius: [4, 4, 0, 0]  // 顶部圆角
			}
		}
	]
});

const resize = () => {
	nextTick(() => {
		if (myChart.value) {
			myChart.value.resize({
				width: 'auto',
				height: 'auto'
			});
		}
	});
};
let resizeTimer = null;
window.addEventListener('resize', () => {
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout(resize, 200);
});
let pendingData = null;

watch(
	() => props.data,
	(newValue) => {
		pendingData = newValue;
		if (myChart.value) {
			updateChart(newValue);
		}
	},
	{ immediate: true }
);

onMounted(() => {
	nextTick(() => {
		try {
			myChart.value = Echarts.init(chartDom.value);
			myChart.value.setOption(options.value);
			if (pendingData !== null) {
				updateChart(pendingData);
				pendingData = null;
			}
		} catch (error) {
			console.error('ECharts 初始化失败:', error);
		}
	});
	window.addEventListener('resize', resize);
});

function updateChart(value) {
	options.value.xAxis.data = value.xData;
	options.value.series[0].data = value.yData;
	options.value.title.text = props.title;
	myChart.value.setOption(options.value);
}

onUnmounted(() => {
	window.removeEventListener('resize', resize);
	if (myChart.value) {
		myChart.value.dispose();
	}
});
</script>

<style scoped lang="scss">
/* 可以在这里添加样式 */
</style>